package com.example.datajpa.controller;

import com.example.datajpa.domain.Person;
import com.example.datajpa.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ljw
 * @description
 * @date 2022/5/20 7:54
 */
@RestController
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    /**
     * 保存
     * @param
     * @author ljw
     * @date 2022/5/20 7:57
     */
    @RequestMapping("/save")
    public Person save(@RequestParam String name, @RequestParam String address, @RequestParam Integer age) {
        Person person = personRepository.save(new Person(null, name, age, address));
        return person;
    }

    /**
     * 根据地址查询
     * @param
     * @author ljw
     * @date 2022/5/20 8:00
     */
    @GetMapping("/findByAddress")
    public List<Person> findByAddress(@RequestParam String address) {
        List<Person> personList = personRepository.findByAddress(address);
        return personList;
    }

    /**
     * 根据名字和地址查询
     * @param
     * @author ljw
     * @date 2022/5/20 8:03
     */
    @GetMapping("/findByNameAndAddress")
    public Person findByNameAndAddress(@RequestParam String name, @RequestParam String address) {
        Person person = personRepository.findByNameAndAddress(name, address);
        return person;
    }

    /**
     * 根据名字和地址查询
     * @param
     * @author ljw
     * @date 2022/5/20 8:07
     */
    @GetMapping("/withNameAndAddressQuery")
    public Person withNameAndAddressQuery(@RequestParam String name, @RequestParam String address) {
        Person person = personRepository.withNameAndAddressQuery(name, address);
        return person;
    }

    /**
     * 根据名字和地址查询
     * @param
     * @author ljw
     * @date 2022/5/20 8:07
     */
    @GetMapping("/withNameAndAddressNamedQuery")
    public Person withNameAndAddressNamedQuery(@RequestParam String name, @RequestParam String address) {
        Person person = personRepository.withNameAndAddressNamedQuery(name, address);
        return person;
    }

    /**
     * 排序
     * @param
     * @author ljw
     * @date 2022/5/20 8:11
     */
    @GetMapping("/sort")
    public List<Person> sort() {
        List<Person> personList = personRepository.findAll(Sort.by(Sort.Direction.ASC, "age"));
        return personList;
    }

    @GetMapping("/page")
    public Page<Person> page() {
        Page<Person> page = personRepository.findAll(PageRequest.of(1, 2));
        return page;
    }
}
